﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Xml;
using System.Drawing.Imaging;
using System.Configuration;


using WCFMINERP.Order.IView;
using WCFMINERP.Order.Forms;
using WCFMINERP.MODEL.Order;
using WCFMINERP.MODEL;
using WCFMINERP.COM;

using Leadtools.Codecs;
using Leadtools;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors.Repository;


namespace WCFMINERP.Order.Presenter
{ 
    public  class OrderPresenter
    {
        ///<summary>
        ///被选中添加照片的产品
        ///</summary>
        public OrderInfo orderInfoSelectedToAddPhotos;
        public List<OrderInfo> _orderInfoList = new List<OrderInfo>();//待开单产品集合
        public List<ProductInfo> _producList;//产品列表

        private IOrderView _view;
        /// <summary>
        /// 所有产品分类列表
        /// </summary>
        private List<ProductCategoryInfo> _productCategoryList = new List<ProductCategoryInfo>();
        /// <summary>
        /// 常用产品列表
        /// </summary>
        private List<ProductInfo> _dailyProductList;
        /// <summary>
        /// 默认纸型
        /// </summary>
        private PaperTypeInfo defaultPaperTypeInfo;
        /// <summary>
        /// 默认纸面
        /// </summary>
        private PaperFaceInfo defaultPaperFaceInfo;
        /// <summary>
        /// 照片crc码列表
        /// </summary>
        private List<PhotoCRCInfo> _PhotoCRCList = new List<PhotoCRCInfo>();

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="view"></param>
        public OrderPresenter(IOrderView view)
        {
            
            _view = view;
            defaultPaperFaceInfo = GetDefaultPaperFaceInfo();
            defaultPaperTypeInfo = GetDefaultPaperTypeInfo();
            _producList = GetAllProductList();
            _dailyProductList = new List<ProductInfo>();
     
        }
        /// <summary>
        /// 绑定产品分类
        /// </summary>
        /// <param name="flp"></param>
        public void LinkProductCategory(FlowLayoutPanel flpGategory)
        {
            LinkPaperFace();
            LinkPaperType();
            if (_productCategoryList.Count == 0)//没有获取到产品分类
            {
                _productCategoryList = GetProductGategoryList();
            }
            CreateControls(flpGategory, _productCategoryList,true);
        }

         /// <summary>
         /// 创建产品分类按钮
         /// </summary>
         /// <param name="flpGategory">布局控件</param>
         /// <param name="productgategoryList">全部产品分类列表</param>
         /// <param name="isAllProductGategory">true为全部产品分类列表，false为常用产品分类列表</param>
        public void CreateControls(FlowLayoutPanel flpGategory,List<ProductCategoryInfo> productgategoryList,bool isAllProductGategory)
        {
            //flpGategory.Controls.Clear();
            if (flpGategory.Controls.Count == 0)//如果还没画分类控件
            {
                foreach (var item in productgategoryList)
                {
                    Button pcg = new Button();
                    //pcg.Tag = isAllProductGategory;//是否为全部产品分类模式
                    pcg.Width = 80;
                    pcg.Height = 60;
                    pcg.Text = item.ProductCategoryName;
                    pcg.Click += new EventHandler(pcg_Click);
                    item.button = pcg;
                    flpGategory.Controls.Add(pcg);
                }
            }
        }

        /// <summary>
        /// 创建产品按钮
        /// </summary>
        /// <param name="flpGategory">布局控件</param>
        /// <param name="productgategoryList">常用产品列表</param>
        /// <param name="showProductNum">最大显示的产品数</param>
        public void CreateProductControls(FlowLayoutPanel flpProduct, List<ProductInfo> productList,uint showProductNum)
        {
            int count;
            if (showProductNum < productList.Count)
            {
                count = (int)showProductNum;
            }
            else
            {
                count =productList.Count;
            }
            flpProduct.Controls.Clear();
            for (int i =0;i< count;i++)
            {
                Button btn = new Button();
                btn.AllowDrop = true;
                btn.Height = 60;
                btn.Width = 80;
                btn.Text = productList[i].productName;
                //btn.Tag = true;
                //btn.ControlCollection.
                btn.DragEnter += new DragEventHandler(btn_DragEnter);
                btn.DragDrop += new DragEventHandler(btn_DragDrop);
                btn.DoubleClick +=new EventHandler(btn_DoubleClick);

                OrderInfo oi = _orderInfoList.FirstOrDefault(o => o.ControlName == productList[i].productName);
                if (oi!=null)//如果这个产品拖过照片
                {
                    btn.BackColor = Color.Pink;
                }
                flpProduct.Controls.Add(btn);
            }
            
        }
        /// <summary>
        /// 点击产品分类按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void pcg_Click(object sender, EventArgs e)
        {

            #region 设置控件
            SplitContainer split1 = (SplitContainer)((Button)sender).Parent.Parent.Parent.Parent;
            split1.Panel2Collapsed = false;
            split1.Panel1Collapsed = true;

            _view.FlpProduct.Parent.Text = ((Button)sender).Text + "==>产品名称";
            #endregion
            string producyGategoryName =((Button)sender).Text;
            ProductCategoryInfo productCategory ;

            productCategory = _productCategoryList.Find(p => p.ProductCategoryName == producyGategoryName);//通过button上的产品分类名字找到产品分类对象
            CreateProductControls(_view.FlpProduct, productCategory.productList, 10000);
        }
        /// <summary>
        /// 双击产品按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_DoubleClick(object sender, EventArgs e)
        {
            string productName =((Button)sender).Text;
            List<OrderInfo> orderInfoList = _orderInfoList.Where(o => o.ControlName == productName).ToList();
            if (orderInfoList.Count > 0)
            {
                FrmOrderInfo frm = new FrmOrderInfo(orderInfoList);
                frm.showtype = ShowType.addPhoto;
                frm.ShowDialog();
            }
        }

        void btn_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
            else e.Effect = DragDropEffects.None;

        }

        /// <summary>
        /// 拖动照片到产品模板上发生的拖动事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btn_DragDrop(object sender, DragEventArgs e)
        {

            bool isChangeColor = true;
            Button btn = (Button)sender;
            ProductInfo productinfo;
     
                productinfo = _producList.Find(p => p.productName == btn.Text.Trim());
                try
                {
                    Cursor.Current = Cursors.WaitCursor;
                    var filePath = (string[])e.Data.GetData(DataFormats.FileDrop);//获取拖拽过来的文件夹列表

                    foreach (var item in filePath)
                    { 
                        if (!Directory.Exists(item))
                        {
                            MessageBox.Show("请拖拽文件的文件夹", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                            isChangeColor = false;
                            continue;
                        }
                        DirectoryInfo dir = new DirectoryInfo(item);
                        List<OrderInfo> OrderInfosOnTheButton = _orderInfoList.Where(o => o.ControlName == btn.Text && o.CtmName == dir.Parent.ToString()).ToList();//同一客户在该控件上已经拖好的产品列表
                        if (OrderInfosOnTheButton.Count > 0)
                        {
                            string productName = dir.Name + "_" + btn.Text;
                            OrderInfo oi = OrderInfosOnTheButton.FirstOrDefault(o => o.OrderProductName == productName);
                            if (oi != null)
                            {
                                if (DialogResult.OK != MessageBox.Show("该文件夹的照片已经拖到了这个产品上，是否继续？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                                {
                                    //isChangeColor = false;
                                    continue;
                                }
                            }
                        }
                        List<OrderInfo> OrderInfosOnTheButton2 = _orderInfoList.Where(o => o.OrderProductName.Substring(0, o.OrderProductName.LastIndexOf("_")) == dir.Name && o.CtmName == dir.Parent.ToString()).ToList();//同意客人的同一文件夹反复拖提示
                        if (OrderInfosOnTheButton2.Count > 0)
                        {
                            //if (DialogResult.OK != MessageBox.Show("该文件夹的照片已经拖到了这个产品上，是否继续？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))
                            //{
                            //    isChangeColor = false;
                            //    continue;
                            //}
                            isChangeColor = false;
                            MessageBox.Show("该文件夹的照片已经开过单，不能重复开单，确定要重复开单请复制该文件夹", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            continue;
                        }
                        if (dir.FullName.Contains("OK"))
                        {
                            isChangeColor = false;
                            MessageBox.Show("该文件夹的照片已经开过单，不能重复开单，确定要重复开单请复制该文件夹,并重命名该文件夹", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            continue;
                        }
                        if (OrderInfosOnTheButton.Count <= 0)//该客户在这个产品上还没有拖照片
                        {

                            OrderInfo oi = CreateOrderInfo(item, productinfo, btn.Text);  //创建新产品
                            _orderInfoList.Add(oi);//将新创建的产品添加到待开单产品列表中
                        }
                        else if (DialogResult.OK != MessageBox.Show("该客户已存在该产品，是否将这些照片合并到之前的产品中？", "询问", MessageBoxButtons.OKCancel, MessageBoxIcon.Question))//同一客户多个相同产品文件夹分开开单
                        {
                            OrderInfo oi = CreateOrderInfo(item, productinfo, btn.Text.ToString());  //创建新产品
                            _orderInfoList.Add(oi);//将新创建的产品添加到待开单产品列表中
                        }
                        else //同一客户多个相同产品文件夹开到一个产品中
                        {
                            if (OrderInfosOnTheButton.Count == 1)//只有一个产品就默认合并到该产品中
                            {
                                OrderInfo oi = OrderInfosOnTheButton[0];
                                GetphotoInfoList(item, oi);
                                UpdatePhotoNumOnOrderInfoControl(oi.PhotoList.Count.ToString(), oi.OrderProductId);

                            }
                            else//有多个产品则弹出产品列表供其选择要合并的产品
                            {

                                FrmOrderInfo frm = new FrmOrderInfo(OrderInfosOnTheButton);
                                frm._presenter = this;
                                frm.showtype = ShowType.Merger;
                                frm.ShowDialog();
                                GetphotoInfoList(item, orderInfoSelectedToAddPhotos);
                                UpdatePhotoNumOnOrderInfoControl(orderInfoSelectedToAddPhotos.PhotoList.Count.ToString(), orderInfoSelectedToAddPhotos.OrderProductId);
                            }

                        }
                    }
                    if (isChangeColor)
                    {
                        btn.BackColor = Color.Pink;
                    }

                    LinkOrderInfo();
                    _view.LinkCommonChargeItem();//绑定公共计价项目
                }
                catch (Exception exx)
                {

                    MessageBox.Show(exx.Message);
                }
                finally
                {
                    Cursor.Current = Cursors.Default;
                }
        }
       
        /// <summary>
        /// 创建一个产品的信息
        /// </summary>
        /// <param name="productFilePath"></param>
        /// <param name="productinfo"></param>
        /// <param name="controlName"></param>
        /// <returns></returns>
        private OrderInfo CreateOrderInfo(string productFilePath,ProductInfo productinfo,string controlName)
        {
            DirectoryInfo dir = new DirectoryInfo(productFilePath);

            OrderInfo orderInfo = new OrderInfo();
            //orderInfo.OrderProductId = Properties.Settings.Default.OrderInfoNo;
            orderInfo.OrderProductId =0;//id无用
            orderInfo.CtmName = dir.Parent.ToString();
            orderInfo.Height = (float)productinfo.height;
            orderInfo.OrderPath = dir.Parent.ToString() + "\\" + dir.Name;
            orderInfo.OrderProductName = dir.Name + "_" + productinfo.productName;
            orderInfo.PageNum = productinfo.pageNum;
            orderInfo.PrePriceCount = 0;
            orderInfo.Priority = 0;
            orderInfo.productNum = 1;
            orderInfo.Status = 0;
            orderInfo.Width = (float)productinfo.width;
            orderInfo.Remark = "";
            orderInfo.ProductId = productinfo.productid;
            orderInfo.ControlName = controlName;
            orderInfo.PaperFaceName = defaultPaperFaceInfo.PaperFaceName;
            orderInfo.PaperTypeName = defaultPaperTypeInfo.paperTypeName;
            orderInfo.OrilOrderPath = productFilePath;///添加产品原路径
            //orderInfo.CommonChargeItemName = productinfo.CommonChargeItemIdList;
            GetphotoInfoList(productFilePath, orderInfo);//生成照片信息

            //Properties.Settings.Default.OrderInfoNo = orderInfo.OrderProductId + 1;
            //Properties.Settings.Default.Save();

            _view.FlpShowOrderInfo.Controls.Add(new UCOrderInfo(orderInfo.ControlName,orderInfo.CtmName,orderInfo.PhotoList.Count.ToString(),orderInfo.OrderProductId));

            return orderInfo;

  
        }

        /// <summary>
        /// 绑定产品列表
        /// </summary>
        private void LinkOrderInfo()
        {

            //gcOrderInfo.DataSource = orderInfoDic.Values.ToList();
            _view.GcOrderInfo.DataSource = _orderInfoList;
            _view.GcOrderInfo.RefreshDataSource();

 
        }

        /// <summary>
        /// 生成photoInfoList
        /// </summary>
        /// <param name="path">文件或文件夹路径</param>
        public List<PhotoInfo> GetphotoInfoList(List<string> pathList)
        {
            List<PhotoInfo> piList = new List<PhotoInfo>();
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();

            foreach (var item in pathList)
            {
                FileInfo fileinfo = new FileInfo(item);
                CodecsImageInfo img = codecs.GetInformation(item, true);
                PhotoInfo photoinfo = new PhotoInfo()
                {

                    Height = img.Height / img.YResolution,
                    OrilPicPath = item,
                    PaperFaceId = defaultPaperFaceInfo.PaperFaceId,
                    PaperTypeID = defaultPaperTypeInfo.paperTypeId,
                    PaperFaceName = defaultPaperFaceInfo.PaperFaceName,
                    PaperTypeName = defaultPaperTypeInfo.paperTypeName,
                    PhotoName = fileinfo.Name,
                    PixHeight = img.Height,
                    PixWidth = img.Width,
                    Width = img.Width / img.XResolution,
                    TotalNum = 1,
                    PicPath =fileinfo.Name,
                    Photoid = Properties.Settings.Default.PhotoInfoNo
                };
                Properties.Settings.Default.PhotoInfoNo = photoinfo.Photoid + 1;
                Properties.Settings.Default.Save();
                piList.Add(photoinfo);
            }
            RasterCodecs.Shutdown();
            return piList;
        }

        /// <summary>
        /// 生成photoInfoList
        /// </summary>
        /// <param name="path">文件或文件夹路径</param>
        private void GetphotoInfoList(string path, OrderInfo orderproductInfo)
        {

            List<string> pathList = new List<string>();

            GetAllPicByDir(path, pathList);
            RasterCodecs.Startup();
            RasterCodecs codecs = new RasterCodecs();

            foreach (var item in pathList)
            {
                FileInfo fileinfo = new FileInfo(item);
                CodecsImageInfo img = codecs.GetInformation(item, true);
                //img.
                PhotoInfo photoinfo = new PhotoInfo()
                {

                    Height = img.Height / img.YResolution,
                    OrilPicPath = item,
                    PaperFaceId = defaultPaperFaceInfo.PaperFaceId,
                    PaperTypeID = defaultPaperTypeInfo.paperTypeId,
                    PaperFaceName = defaultPaperFaceInfo.PaperFaceName,
                    PaperTypeName = defaultPaperTypeInfo.paperTypeName,
                    PhotoName = fileinfo.Name,
                    PixHeight = img.Height,
                    PixWidth = img.Width,
                    Width = img.Width / img.XResolution,
                    TotalNum = 1,
                    PicPath = item.Substring(path.Length + 1),
                    //Photoid = Properties.Settings.Default.PhotoInfoNo,
                    Photoid = 0,//id无用
                    OrderInfoId = orderproductInfo.OrderProductId,
                    Resolution = img.XResolution//分辨率

                };
                //Properties.Settings.Default.PhotoInfoNo = photoinfo.Photoid + 1;
                //Properties.Settings.Default.Save();

                orderproductInfo.PhotoList.Add(photoinfo);
            }
            RasterCodecs.Shutdown();

        }

       
        /// <summary>
        /// 绑定常用产品
        /// </summary>
        /// <param name="productInfoList"></param>
        /// <param name="flp"></param>
        public void LinkDailyProducts(FlowLayoutPanel flp)
        {
            LinkPaperFace();
            LinkPaperType();

             _dailyProductList = GetProductDailyList();
            
            CreateProductControls(flp, _dailyProductList,Properties.Settings.Default.ShowDailyProductNum);
        }

        /// <summary>
        /// 绑定模板产品
        /// </summary>
        /// <param name="flp"></param>
        /// <param name="templateName"></param>
        public void LinkTemplateProducts(FlowLayoutPanel flp, string templateName)
        {
            LinkPaperFace();
            LinkPaperType();
            CreateProductControls(flp, GetTemplateProductInfoList(templateName), Properties.Settings.Default.ShowDailyProductNum);
        }

        /// <summary>
        /// 绑定查找产品
        /// </summary>
        /// <param name="flp"></param>
        /// <param name="productName"></param>
        public void LinkQueryProuducts(FlowLayoutPanel flp, string productName)
        {
            if (!string.IsNullOrEmpty(productName))
            {
                List<ProductInfo> productlist = _producList.Where(p => p.mnemonicCode.Contains(productName)).ToList();
                if (productlist.Count < 1)
                {
                    productlist = _producList.Where(p => p.productName.Contains(productName)).ToList();
                }
                CreateProductControls(flp, productlist, 10000);
            }
        }
        
        /// <summary>
        /// 获取模板上的产品列表
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        private List<ProductInfo> GetTemplateProductInfoList(string templateName)
        {
            List<ProductInfo> productInfoList = new List<ProductInfo>();
            foreach (var item in GetProductTemplateInfo(templateName).ProductIdList)
            {
                productInfoList.Add(_producList.Find(p => p.productid == item));
            }
            return productInfoList;
        }

       /// <summary>
        /// 点击下单后生产xml文件
       /// </summary>
       /// <param name="inOrderBag"></param>
       /// <returns>返回错误代码</returns>
        public int OrderAndProductXml(OrderBag inOrderBag)
        {
            if (_orderInfoList.Count < 1)
            {
                return -1;//产品列表未初始化
            }
            if (Properties.Settings.Default.CurrentDate.ToShortDateString() == DateTime.Now.ToShortDateString())
            {
                inOrderBag.SerialNum = Properties.Settings.Default.SerialNo + 1;
                Properties.Settings.Default.SerialNo = inOrderBag.SerialNum;
                Properties.Settings.Default.Save();
            }
            else
            {
                inOrderBag.SerialNum = 1;
                Properties.Settings.Default.SerialNo = 1;
                Properties.Settings.Default.CurrentDate = DateTime.Now;
                Properties.Settings.Default.Save();

            }
            
            string xmlpath =Environment.CurrentDirectory+"\\OrderFileTemp";//订单xml文件保存路径
            if (!Directory.Exists(xmlpath + "\\S" + inOrderBag.ShopId.ToString("0000") + DateTime.Now.ToString("yyyyMMdd") + inOrderBag.SerialNum.ToString("0000")))
            {
                Directory.CreateDirectory(xmlpath + "\\S" + inOrderBag.ShopId.ToString("0000") + DateTime.Now.ToString("yyyyMMdd") + inOrderBag.SerialNum.ToString("0000"));
            }
            inOrderBag.RARName = "S" + inOrderBag.ShopId.ToString("0000") + DateTime.Now.ToString("yyyyMMdd") + inOrderBag.SerialNum.ToString("0000");
            inOrderBag.OrderbagName = DateTime.Now.ToString("yyyyMMdd")+ inOrderBag.SerialNum.ToString("0000");
            inOrderBag.OrderTime = DateTime.Now;
            inOrderBag.OrderInfoList = _orderInfoList;
            ProductXml(inOrderBag, xmlpath);

            _orderInfoList.Clear();
            LinkOrderInfo();
            _view.ClearProductStatus();
            return 0;//正常结束
        }
        /// <summary>
        /// 生成照片的CRC码xml文件
        /// </summary>
        /// <param name="photoList"></param>
        private void ProducePhotoCRCCodeXml(List<PhotoInfo> photoList)
        {
            string xmlPath = Environment.CurrentDirectory + "\\PhotoCRCCode.xml";
        }
        /// <summary>
        /// 根据内存中的数据组织XML并保存
        /// </summary>
        /// <param name="inOrderBag"></param>
        /// <param name="savePath"></param>
        public void ProductXml(OrderBag inOrderBag, string savePath)
        {

            XmlDocument newBagXml = new XmlDocument();
            XmlDeclaration xd = newBagXml.CreateXmlDeclaration("1.0", "utf-8", null);
            newBagXml.AppendChild(xd);

            XmlProcessingInstruction xpi = newBagXml.CreateProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"orderbag.xsl\"");
            newBagXml.AppendChild(xpi);
            //XmlNode xn = newBagXml.CreateNode(XmlNodeType.Element, "orderbag", null);

            //XmlAttribute xa = newBagXml.CreateAttribute("OrderbagID");
            //xa.Value = "";
            XmlElement xeOrderBag = newBagXml.CreateElement("orderbag");//orderbag元素
            xeOrderBag.SetAttribute("OrderbagID", inOrderBag.OrderbagID.ToString());
            xeOrderBag.SetAttribute("SerialNum", inOrderBag.SerialNum.ToString());
            xeOrderBag.SetAttribute("OrderbagName", inOrderBag.OrderbagName);
            xeOrderBag.SetAttribute("RARName", inOrderBag.RARName);
            xeOrderBag.SetAttribute("ShopId", inOrderBag.ShopId.ToString());
            xeOrderBag.SetAttribute("OrderTime", inOrderBag.OrderTime.ToString("yyyy-MM-dd HH:mm:ss"));
            xeOrderBag.SetAttribute("FetchTime", inOrderBag.FetchTime.ToString("yyyy-MM-dd HH:mm:ss"));
            xeOrderBag.SetAttribute("Status", inOrderBag.Status.ToString());
            xeOrderBag.SetAttribute("Priority", inOrderBag.Priority.ToString());
            xeOrderBag.SetAttribute("PrePriceCount", inOrderBag.PrePriceCount.ToString("0.00"));
            xeOrderBag.SetAttribute("Remark", inOrderBag.Remark);

            newBagXml.AppendChild(xeOrderBag);

            //List<OrderInfo> orderList = inOrderBag.OrderInfoList;
            foreach (OrderInfo order in inOrderBag.OrderInfoList)
            {
                ///产品元素
                XmlElement xeorder = newBagXml.CreateElement("orderinfo");
                xeorder.SetAttribute("OrderProductId", order.OrderProductId.ToString());
                xeorder.SetAttribute("OrderProductName", order.OrderProductName.ToString());
                xeorder.SetAttribute("ProductId", order.ProductId.ToString());
                xeorder.SetAttribute("CtmName", order.CtmName.ToString());
                xeorder.SetAttribute("Status", order.Status.ToString());
                xeorder.SetAttribute("Width", order.Width.ToString());
                xeorder.SetAttribute("Height", order.Height.ToString());
                xeorder.SetAttribute("productNum", order.productNum.ToString());
                xeorder.SetAttribute("PageNum", order.PageNum.ToString());
                xeorder.SetAttribute("PrePriceCount", order.PrePriceCount.ToString());
                xeorder.SetAttribute("Priority", order.Priority.ToString());
                xeorder.SetAttribute("Remark", order.Remark.ToString());
                xeorder.SetAttribute("OrderPath", order.OrderPath.ToString());
                xeorder.SetAttribute("CommonChargeItem", order.CommonChargeItemIdList);
                xeorder.SetAttribute("OrilOrderPath", order.OrilOrderPath);
                xeOrderBag.AppendChild(xeorder);
                foreach (PhotoInfo photo in order.PhotoList)
                {
                    ///照片元素
                    XmlElement xePhoto = newBagXml.CreateElement("photoInfo");
                    xePhoto.SetAttribute("Photoid", photo.Photoid.ToString());
                    xePhoto.SetAttribute("photoName", photo.PhotoName.ToString());
                    xePhoto.SetAttribute("picPath", photo.PicPath.ToString());
                    xePhoto.SetAttribute("OrilPicPath", photo.OrilPicPath.ToString());
                    xePhoto.SetAttribute("Width", photo.Width.ToString());
                    xePhoto.SetAttribute("Height", photo.Height.ToString());
                    xePhoto.SetAttribute("pixWidth", photo.PixWidth.ToString());
                    xePhoto.SetAttribute("Pixheight", photo.PixHeight.ToString());
                    xePhoto.SetAttribute("paperTypeID", photo.PaperTypeID.ToString());
                    xePhoto.SetAttribute("paperFaceId", photo.PaperFaceId.ToString());
                    xePhoto.SetAttribute("TotalNum", photo.TotalNum.ToString());
                    xePhoto.SetAttribute("Photoid", photo.Photoid.ToString());
                    xePhoto.SetAttribute("Photoid", photo.Photoid.ToString());
                    xeorder.AppendChild(xePhoto);
                }

            }
            savePath += "\\" + "S" + inOrderBag.ShopId.ToString("0000") + "" + DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + inOrderBag.SerialNum.ToString("0000");
            newBagXml.Save(savePath + "\\" + "S" + inOrderBag.ShopId.ToString("0000") + "" + DateTime.Now.ToString("yyyy-MM-dd").Replace("-", "") + inOrderBag.SerialNum.ToString("0000") + ".xml");

        }
        /// <summary>
        /// 根据文件包拷贝文件并准备压缩
        /// </summary>
        /// <param name="inOrderBag"></param>
        public void CopyFile(OrderBag inOrderBag, string inWorkFolder)
        {
            foreach (OrderInfo order in inOrderBag.OrderInfoList)
            {
                string strOrderPath = inWorkFolder + "\\" + order.OrderPath;//产品路径
                if (!Directory.Exists(strOrderPath))
                {
                    Directory.CreateDirectory(strOrderPath);
                }
                foreach (PhotoInfo photo in order.PhotoList)
                {
                    int subIndex = photo.PicPath.ToLower().LastIndexOf(".jpg");
                    if (subIndex == 0)
                    {
                        subIndex = photo.PicPath.ToLower().LastIndexOf(".jpeg");
                    }

                    string photoDirpath = photo.PicPath.Substring(0, subIndex);
                    if (!Directory.Exists(photoDirpath))
                    {
                        Directory.CreateDirectory(photoDirpath);
                    }
                    if (!File.Exists(photo.OrilPicPath))
                    {
                        ///文件不存在报错处理
                        throw new Exception();
                    }
                    //复制文件
                    if (FileOperate.CopyFile(photo.OrilPicPath, strOrderPath + "\\" + photo.PicPath, true))
                    {

                    }
                    else
                    {
                        ///文件不存在报错处理
                        throw new Exception();
                    }

                }

            }


        }

        /// <summary>
        /// 递归找到文件夹下所有照片文件
        /// </summary>
        /// <param name="inPath"></param>
        /// <param name="inList"></param>
        public void GetAllPicByDir(string inPath, List<string> inList)
        {
            //if (isStop)
            //{
            //    return;
            //}
            string picTag = ".JPEG.JPG.TIF.BMP.TIFF";
            DirectoryInfo rootDir = new DirectoryInfo(inPath);
            if (rootDir.Exists)
            {
                FileInfo[] fileList = rootDir.GetFiles();
                foreach (FileInfo info in fileList)
                {
                    //if (isStop)
                    //{
                    //    return;
                    //}
                    if (picTag.Contains(info.Extension.ToUpper()))
                    {
                        inList.Add(info.FullName);
                    }
                    else
                    {
                        if (info.FullName.ToUpper().IndexOf(("Thumbs.db").ToUpper()) == -1 && !info.FullName.ToUpper().EndsWith("TXT"))
                        {
                            _view.ShowImportMessage(DateTime.Now + " 导片时发现不能处理的文件：" + info.FullName);
                        }
                    }
                }
                DirectoryInfo[] listDir = rootDir.GetDirectories();
                foreach (DirectoryInfo dir in listDir)
                {
                    GetAllPicByDir(dir.FullName, inList);
                }
            }

        }

        /// <summary>
        ///  获取全部产品分类
        /// </summary>
        /// <returns></returns>
        private List<ProductCategoryInfo> GetProductGategoryList()
        {
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";
            List<ProductCategoryInfo> productGategoryList = new List<ProductCategoryInfo>();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/productInfo");

            foreach (XmlNode xmlProduct in xmlnodeList)
            {
                bool isproductgategoryExsit = false;
                foreach (var productGategory in productGategoryList)
                {
                    if (productGategory.ProductCategoryName == xmlProduct.Attributes["productCategoryName"].Value)
                    {
                        isproductgategoryExsit = true;
                        productGategory.productList.Add(GetProductInfo(xmlProduct));
                        break;
                    }

                }
                if (!isproductgategoryExsit)
                {
                    ProductCategoryInfo productCategoryInfo = new ProductCategoryInfo();
                    productCategoryInfo.ProductCategoryName = xmlProduct.Attributes["productCategoryName"].Value;
                    productCategoryInfo.productList = new List<ProductInfo>();
                    productCategoryInfo.productList.Add(GetProductInfo(xmlProduct));
                    productGategoryList.Add(productCategoryInfo);
                }
            }

            return productGategoryList;
        }


        /// <summary>
        /// 获取全部产品列表
        /// </summary>
        /// <returns></returns>
        private List<ProductInfo> GetAllProductList()
        {
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";
            List<ProductInfo> productList = new List<ProductInfo>();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/productInfo");

            foreach (XmlNode xmlProduct in xmlnodeList)
            {
                
                productList.Add(GetProductInfo(xmlProduct));
                
            }
            return productList.OrderByDescending(p => p.usedTimes).ToList();//按使用次数递减排序后返回常用产品列表
 
        }

        /// <summary>
        ///  获取常用产品列表
        /// </summary>
        /// <returns></returns>
        private List<ProductInfo> GetProductDailyList()
        {
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";
            //List<ProductCategoryInfo> productGategoryList = new List<ProductCategoryInfo>();
            List<ProductInfo> productList = new List<ProductInfo>();

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/productInfo");

            foreach (XmlNode xmlProduct in xmlnodeList)
            {
                if (Convert.ToInt32(xmlProduct.Attributes["usedTimes"].Value) > 0)//如果产品使用次数大于零
                {
                    productList.Add(GetProductInfo(xmlProduct));
                }
            }
            return productList.OrderByDescending(p=>p.usedTimes).ToList();//按使用次数递减排序后返回常用产品列表
        }

        /// <summary>
        /// 获得产品对象
        /// </summary>
        /// <param name="xmlProduct"></param>
        /// <returns></returns>
        private ProductInfo GetProductInfo(XmlNode xmlProduct)
        {
            ProductInfo productInfo = new ProductInfo()
            {
                appendPrice = Convert.ToDecimal(xmlProduct.Attributes["appendPrice"].Value),
                areaPrice = Convert.ToDecimal(xmlProduct.Attributes["areaPrice"].Value),
                costTypeName = xmlProduct.Attributes["costTypeName"].Value,
                coverHeight = Convert.ToDouble(xmlProduct.Attributes["coverHeight"].Value),
                coverWidth = Convert.ToDouble(xmlProduct.Attributes["coverWidth"].Value),
                height = Convert.ToDouble(xmlProduct.Attributes["height"].Value),
                mnemonicCode = xmlProduct.Attributes["mnemonicCode"].Value,
                pageNum = Convert.ToInt32(xmlProduct.Attributes["pageNum"].Value),
                productCategoryName = xmlProduct.Attributes["productCategoryName"].Value,
                productid = Convert.ToInt32(xmlProduct.Attributes["productid"].Value),
                productName = xmlProduct.Attributes["productName"].Value,
                status = Convert.ToInt32(xmlProduct.Attributes["status"].Value),
                unitPrice = Convert.ToDecimal(xmlProduct.Attributes["unitPrice"].Value),
                width = Convert.ToDouble(xmlProduct.Attributes["width"].Value),
                usedTimes =Convert.ToInt32(xmlProduct.Attributes["usedTimes"].Value),
                CommonChargeItemIdList = (xmlProduct.Attributes["CommonChargeItemIdList"].Value).ToString()
            };
            return productInfo;
        }

        /// <summary>
        /// 获取商户默认纸面
        /// </summary>
        /// <returns></returns>
        private PaperFaceInfo GetDefaultPaperFaceInfo()
        {
            PaperFaceInfo paperFaceInfo = null;
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";
            
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/paperFace");

            foreach (XmlNode xmlProduct in xmlnodeList)
            {
                bool isdefault =Convert.ToBoolean(xmlProduct.Attributes["defaultPaperFace"].Value);
                if (isdefault)
                {
                    paperFaceInfo = new PaperFaceInfo()
                    {
                        PaperFaceId = Convert.ToInt32(xmlProduct.Attributes["paperFaceId"].Value),
                        PaperFaceName = xmlProduct.Attributes["paperFaceName"].Value
                    };
                    break;
                }
            }
            return paperFaceInfo;
        }


        /// <summary>
        /// 获取商户默认纸型
        /// </summary>
        /// <returns></returns>
        private PaperTypeInfo GetDefaultPaperTypeInfo()
        {
            PaperTypeInfo paperTypeInfo = null;
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";
            
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/paperType");
            foreach (XmlNode item in xmlnodeList)
            {
                bool isdefault = Convert.ToBoolean(item.Attributes["defaultPaperType"].Value);
                if (isdefault)
                {
                    paperTypeInfo = new PaperTypeInfo()
                    {
                        areaPrice = Convert.ToDecimal(item.Attributes["areaPrice"].Value),
                        paperTypeId = Convert.ToInt32(item.Attributes["paperTypeId"].Value),
                        paperTypeName = item.Attributes["paperTypeName"].Value
                    };

                    break;
                }
                
            }

            return paperTypeInfo;
           
        }

        /// <summary>
        /// 绑定纸面
        /// </summary>
        private void LinkPaperFace()
        {

            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/paperFace");
            _view.cmboxPaperFace.Items.Clear();
            _view.PaperFaceList.Clear();
            _view.cmboxOrderInfoPaperFace.Items.Clear();
            foreach (XmlNode xmlProduct in xmlnodeList)
            {
                _view.cmboxPaperFace.Items.Add(xmlProduct.Attributes["paperFaceName"].Value);
                _view.cmboxOrderInfoPaperFace.Items.Add(xmlProduct.Attributes["paperFaceName"].Value);
                PaperFaceInfo pf = new PaperFaceInfo();
                pf.PaperFaceName = xmlProduct.Attributes["paperFaceName"].Value;
                pf.PaperFaceId = Convert.ToInt32(xmlProduct.Attributes["paperFaceId"].Value);
                _view.PaperFaceList.Add(pf);
            }
        }

        /// <summary>
        /// 绑定纸型
        /// </summary>
        private void LinkPaperType()
        {
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/paperType");
            _view.cmboxPaperType.Items.Clear();
            _view.cmboxOrderInfoPaperType.Items.Clear();
            _view.PaperTypeList.Clear();
            foreach (XmlNode item in xmlnodeList)
            {
                _view.cmboxPaperType.Items.Add(item.Attributes["paperTypeName"].Value);
                _view.cmboxOrderInfoPaperType.Items.Add(item.Attributes["paperTypeName"].Value);
                PaperTypeInfo pt = new PaperTypeInfo();
                pt.paperTypeId =Convert.ToInt32( item.Attributes["paperTypeId"].Value);
                pt.paperTypeName = item.Attributes["paperTypeName"].Value;
                _view.PaperTypeList.Add(pt);
            }

        }

        /// <summary>
        /// 绑定公共收费项目
        /// </summary>
        public void LinkCommonChargeItem()
        {
            XmlNodeList xmlnodeList;
            string xmlpath = Environment.CurrentDirectory + "\\product.xml";

            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlpath);

            xmlnodeList = xmldoc.SelectNodes(@"orderProductInfo/commonChargeItem");
            _view.cmboxCommonChargeItem.Items.Clear();
            _view.CommonChargeItemList.Clear();
            foreach (XmlNode item in xmlnodeList)
            {
                _view.cmboxCommonChargeItem.Items.Add(item.Attributes["CommonChargeItemName"].Value);
                CommonChargeItemInfo commonItem = new CommonChargeItemInfo();
                commonItem.CommonChargeItemId = Convert.ToInt32(item.Attributes["CommonChargeItemId"].Value);
                commonItem.CommonChargeItemName = item.Attributes["CommonChargeItemName"].Value;
                _view.CommonChargeItemList.Add(commonItem);
            }
        }
       
        /// <summary>
        /// 刷新产品控件上的照片数
        /// </summary>
        /// <param name="photoNum"></param>
        public void UpdatePhotoNumOnOrderInfoControl(string photoNum,int orderInfoId)
        {

            foreach (UCOrderInfo item in _view.FlpShowOrderInfo.Controls)
            {
                if (item.OrderInfoId == orderInfoId)
                {
                    item.PhotoNum = photoNum;
                    break;
                }
            }
        }


        /// <summary>
        /// 去掉已删除产品的控件
        /// </summary>
        /// <param name="orderInfoId"></param>
        public void DeleteOrderInfoControl(int orderInfoId)
        {
            foreach (UCOrderInfo item in _view.FlpShowOrderInfo.Controls)
            {
                if (item.OrderInfoId == orderInfoId)
                {
                    _view.FlpShowOrderInfo.Controls.Remove(item);
                    break;
                }
            }
        }


        /// <summary>
        /// 刷新产品按钮的颜色，红色表示该产品已经拖有照片
        /// </summary>
        public void RefreshControlStatus(string productName)
        {
            OrderInfo oi  =_orderInfoList.FirstOrDefault(o=>o.ControlName ==productName);
            if (oi == null)
            {
                foreach (Button item in _view.FlpProduct.Controls)
                {
                    if (item.Text == productName)
                    {
                        item.BackColor = Color.Transparent;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 添加产品模板
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="ListproductId"></param>
        /// <returns></returns>
        public int CreateProductTemplate(string templateName, List<int> ListproductId)
        {
            int ret = 0;
            string xmlPath = Application.StartupPath + "\\productTemplate.xml";
            if (File.Exists(xmlPath))//存在则更新
            {
                List<string> listtemplateName = new List<string>();
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(xmlPath);
                XmlNodeList xmlNodes = xmldoc.SelectNodes(@"ProductTemplate/Template");
                foreach (XmlNode item in xmlNodes)
                {
                    listtemplateName.Add(item.Attributes["Name"].Value);

                }
                if (listtemplateName.Contains(templateName))
                {
                    ret = 1;
                    return ret;
                }
                XmlNode xmlroot = xmldoc.SelectSingleNode(@"ProductTemplate");
                //添加模板
                XmlElement template = xmldoc.CreateElement("Template");
                template.SetAttribute("Name", templateName);
                xmlroot.AppendChild(template);
                //添加模板中的产品
                foreach (var item in ListproductId)
                {
                    XmlElement product = xmldoc.CreateElement("Product");
                    product.SetAttribute("ProductId", item.ToString());
                    template.AppendChild(product);
                }

                xmldoc.Save(xmlPath);
            }
            else//不存在则创建
            {
                XmlDocument xmldoc = new XmlDocument();

                //定义XML文档头文件
                XmlDeclaration xmlDeclaration = xmldoc.CreateXmlDeclaration("1.0", "utf-8", null);
                xmldoc.AppendChild(xmlDeclaration);

                //定义并添加XML的根
                XmlElement xmlroot = xmldoc.CreateElement("ProductTemplate");
                xmldoc.AppendChild(xmlroot);
                //添加模板
                XmlElement template = xmldoc.CreateElement("Template");
                template.SetAttribute("Name", templateName);
                xmlroot.AppendChild(template);
                //添加模板中的产品
                foreach (var item in ListproductId)
                {
                    XmlElement product = xmldoc.CreateElement("Product");
                    product.SetAttribute("ProductId", item.ToString());
                    template.AppendChild(product);
                }

                xmldoc.Save(xmlPath);

            }
            return ret;

        }

        /// <summary>
        /// 更新产品模板
        /// </summary>
        /// <param name="templateName"></param>
        /// <param name="ListproductId"></param>
        /// <returns></returns>
        public int UPdateProductTemplate(string templateName, List<int> ListproductId)
        {
            int ret = 0;
            try
            {

                string xmlPath = Application.StartupPath + "\\productTemplate.xml";
            
                List<string> listtemplateName = new List<string>();
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(xmlPath);
                XmlNode templateNode = null;
                XmlNodeList xmlNodes = xmldoc.SelectNodes(@"ProductTemplate/Template");
                foreach (XmlNode item in xmlNodes)
                {
                    if (item.Attributes["Name"].Value == templateName)
                    {
                        templateNode = item;
                        break;
                    }

                }
               while(templateNode.ChildNodes.Count>0)
               {
                    templateNode.RemoveChild(templateNode.ChildNodes[0]);
               }
               
                //添加模板中的产品
                foreach (var item in ListproductId)
                {
                    XmlElement product = xmldoc.CreateElement("Product");
                    product.SetAttribute("ProductId", item.ToString());
                    templateNode.AppendChild(product);
                }

                xmldoc.Save(xmlPath);
            }
            catch(Exception ex)
            {
            }
            
           
            return ret;

        }

        /// <summary>
        /// 删除产品模板
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        public int DeleteProductTemplate(string templateName)
        {
            int ret = 0;
            string xmlPath = Application.StartupPath + "\\productTemplate.xml";

            List<string> listtemplateName = new List<string>();
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlPath);

            XmlNode rootNode = xmldoc.SelectSingleNode(@"ProductTemplate");
            XmlNode templateNode = null;
            XmlNodeList xmlNodes = xmldoc.SelectNodes(@"ProductTemplate/Template");
            foreach (XmlNode item in xmlNodes)
            {
                if (item.Attributes["Name"].Value == templateName)
                {
                    templateNode = item;
                    break;
                }

            }
            if (templateNode != null)
            {
                rootNode.RemoveChild(templateNode);
            }
            else
            {
                ret = 1;//不存在该节点
            }
            xmldoc.Save(xmlPath);


            return ret;

        }

        /// <summary>
        /// 根据模板名称获得模板信息
        /// </summary>
        /// <param name="templateName"></param>
        /// <returns></returns>
        public ProductTemplateInfo GetProductTemplateInfo(string templateName)
        {
            string xmlPath = Application.StartupPath + "\\productTemplate.xml";
            ProductTemplateInfo templateInfo = new ProductTemplateInfo();
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(xmlPath);
            XmlNodeList nodeList = xmldoc.SelectNodes(@"ProductTemplate/Template");
            XmlNode templateNode=null;
            foreach (XmlNode item in nodeList)
            {
                if (item.Attributes["Name"].Value == templateName)
                {
                    templateNode = item;
                    break;
                }
            }
            templateInfo.TemplateName = templateName;
            foreach (XmlNode item in templateNode.ChildNodes)
            {
                templateInfo.ProductIdList.Add(Convert.ToInt32(item.Attributes["ProductId"].Value));
            }
            return templateInfo;
        }
       
        /// <summary>
        /// 获取所有产品模板名称列表
        /// </summary>
        /// <returns></returns>
        public List<string> GetProductTemplateNames()
        {
            List<string> nameList = new List<string>();
            string xmlPath = Application.StartupPath + "\\productTemplate.xml";
            if (File.Exists(xmlPath))
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.Load(xmlPath);
                XmlNodeList nodeList = xmldoc.SelectNodes(@"ProductTemplate/Template");
                foreach (XmlNode item in nodeList)
                {
                    nameList.Add(item.Attributes["Name"].Value);
                }
            }
            return nameList;
        }

    }
}
